<?php

class template{
	private $templateDir;//存放模板引擎源文件的目录
	private $compileDir;//存放编译之后文件存放的目录
	private $leftTag = '{#';//在模板文件中所要替换的的变量标识符，让模板引擎识别的标记(左边)
	private $righTag = '#}';//被模板引擎识别的标记(左边)
	private $currentTemp = '';//存放当前正在编译的模板文件名
	private $outputHtml;//存放当前正在编译的模板文件中的代码
	private $varPool = array();//在编译模板源文件之前，将模板中变量的值存放在此变量池中

	public function __construct($templateDir,$compileDir,$leftTag = null,$righTag = null){
		$this->templateDir = $templateDir;
		$this->compileDir = $compileDir;
		if(!empty($leftTag))
			$this->leftTag = $leftTag;
		if(!empty($righTag))
			$this->righTag = $righTag;
	}
	//将模板中的变量放到变量池中
	//$tag下标，$var值
	public function assion($tag,$var){
		$this->varPool[$tag] = $var;
	}

	//将变量池中的变量，取出来
	public function getVar($tag){
		return $this->varPool[$tag];
	}


	//获取模板的源文件
	//$templateName源文件的名称，默认模板文件拓展名
	public function getSourceTemplate($templateName,$ext = '.html'){
		//将模板名称赋值给$currentTemp
		$this->currentTemp = $templateName;
		//模板文件的完整路径
		$sourceFilename = $this->templateDir.$this->currentTemp.$ext;
		//获取html代码
		$this->outputHtml = file_get_contents($sourceFilename);


	}

	//编译模板文件
	public function compileTemplate($templateName = null,$ext = '.html'){
		$templateName =empty($templateName)?$this->currentTemp:$templateName;
		//   \{#\$[a-zA-Z]+[\w]*#\}
		$pattern = '/'.preg_quote($this->leftTag);
		$pattern .= ' *\$([a-zA-Z_]\w*) *';
		$pattern .= preg_quote($this->righTag).'/';
		$this->outputHtml = preg_replace($pattern,'<?php echo $this->getVar(\'$1\')?>',$this->outputHtml);
		//
		$compileTemplate =$this->compileDir.md5($templateName).$ext;
		//生成一个目标文件
		file_put_contents($compileTemplate,$this->outputHtml);
	}

	//显示模板
	public function display($templateName = null,$ext = '.html'){
		$templateName =empty($templateName)?$this->currentTemp:$templateName;
		include_once $this->compileDir.md5($templateName).$ext;
	}




}


?>